package com.example.hfweather.ui.home

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextView
import android.widget.Toast
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.hfweather.R
import com.example.hfweather.WeatherGlobal
import com.example.hfweather.adapter.HourAirQualityAdapter
import com.example.hfweather.adapter.HourTempAdapter
import com.example.hfweather.base.BaseBindingFragment
import com.example.hfweather.bean.ChangeCityBean
import com.example.hfweather.databinding.FragmentHomeBinding
import com.example.hfweather.event.ChangeCityClickEvent
import com.example.hfweather.ui.detail.WeatherDetailActivity
import com.example.hfweather.util.WeatherUtils
import com.qweather.sdk.response.air.v1.AirV1CurrentResponse
import com.qweather.sdk.response.air.v1.AirV1HourlyResponse
import com.qweather.sdk.response.weather.WeatherHourlyResponse
import com.qweather.sdk.response.weather.WeatherNowResponse
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(), HomeView {
    //定义dialog
    private var dialog: ChangeCityDialog? = null
    /**
     * 显示切换城市的dialog
     */
    fun showChangeDialog(){
        mActivity?.let {
            dialog = ChangeCityDialog(it, R.style.BottomSheetDialog_Immersion)
            dialog?.setOnDismissListener {
                if(dialog != null){
                    dialog = null
                }
            }
            dialog?.show()
        }
    }

    //周期性更新时间
    // 创建与主线程关联的Handler实例，用于执行定时任务
    private val handler = Handler(Looper.getMainLooper())


    // 定义Runnable对象，用于周期性更新当前时间
    private val updateTimeRunnable = object : Runnable {
        override fun run() {
            showCurrentTime()  // 调用方法更新界面显示的时间
            handler.postDelayed(this, 1000) // 每隔1000毫秒（即1秒）再次执行此任务
        }
    }


    //1.初始化HomePresenter
    private var mPresenter: HomePresenter? = null

    override fun onResume() {
        super.onResume()
        if (binding.topBar.tvCityName.text.isEmpty()) {
            refreshLocationWeatherData(
                WeatherGlobal.getLatitude(),
                WeatherGlobal.getLongitude(),
                WeatherGlobal.getCityName()
            )
        }
    }

    override fun initBinding(
        inflater: LayoutInflater, parent: ViewGroup?
    ): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, parent, false)
    }

    override fun initView() {
        mPresenter = HomePresenter(this, HomeInteractor())
        //设置点击事件监听
        setupClickListener()
        //设置未来24小时天气布局与适配器
        binding.hourlyForecast.rvHourlyForecast.apply {
            //设置布局管理：水平滚动
            layoutManager = LinearLayoutManager(
                requireContext(),
                LinearLayoutManager.HORIZONTAL,
                false
            )
            //设置适配器
            adapter = HourTempAdapter()
            //设置每个单向的间距
            if (binding.hourlyForecast.rvHourlyForecast.itemDecorationCount == 0){
                binding.hourlyForecast.rvHourlyForecast.addItemDecoration(
                    HorizontalSpaceItemDecoration(20,this)
                )
            }
        }
        //设置未来24小时空气质量的布局与适配器
        binding.hourlyAirQuality.rvHourlyAirQuality.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            adapter = HourAirQualityAdapter() // 确保你已经实现了这个适配器
            if (binding.hourlyAirQuality.rvHourlyAirQuality.itemDecorationCount == 0) {
                binding.hourlyAirQuality.rvHourlyAirQuality.addItemDecoration(object :
                    RecyclerView.ItemDecoration() {
                    override fun getItemOffsets(
                        outRect: Rect,
                        view: View,
                        parent: RecyclerView,
                        state: RecyclerView.State
                    ) {
                        super.getItemOffsets(outRect, view, parent, state)
                        val position = parent.getChildAdapterPosition(view)
                        if (position == 0) {
                            outRect.left = 0
                        } else {
                            context?.let {
                                outRect.left = WeatherUtils.dip2px(it, 8f)
                            }
                        }
                    }
                })
            }
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
        stopUpdateTime()
    }


    /**
     * 订阅ChangeCityClickEvent事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun changeCitySuccess(event: ChangeCityClickEvent){
        /**
         * 切换城市成功，刷新数据
         */
        event.changeCityBean.let {
            refreshLocationWeatherData(
                it.latitude.toString(),
                it.longitude.toString(),
                it.cityName)
        }
    }
    private fun setupClickListener() {
        binding.currentWeatherCard.btnRealTime.setOnClickListener {
            showLoading()
            mPresenter?.requestMainWeatherData()
        }

        // 3. 监听顶部栏城市点击事件
        binding.topBar.llChangeCityContainer.setOnClickListener {
            mPresenter?.requestTopCityListData()
            // TODO: 展示城市弹层
            showChangeDialog()
        }

        //4.监听天气卡片点击事件
        binding.currentWeatherCard.root.setOnClickListener {
            // 跳转到天气详情页面
            val intent = Intent(requireContext(), WeatherDetailActivity::class.java)
            // 传递数据 城市经纬度，城市名称
            intent.putExtra("latitude", mPresenter?.getCurrShowLatitude())
            intent.putExtra("longitude", mPresenter?.getCurrShowLongitude())
            intent.putExtra("cityName", mPresenter?.getCurrShowCityName())
            startActivity(intent)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun getMainWeatherDataSuccess(response: WeatherNowResponse) {
        hideLoading()
        // 更新UI
        //显示时间
        stopUpdateTime()
        showCurrentTime()
        startUpdateTime()
        //显示当前天气卡片
        binding.currentWeatherCard.llCurrentWeatherContainer.visibility = ViewGroup.VISIBLE
        binding.currentWeatherCard.tvRefreshTime.text =
            WeatherUtils.formatTime(response.updateTime) + "    更新"
        binding.currentWeatherCard.tvTemperature.text = response.now.temp.toString()
        binding.currentWeatherCard.tvDegreeSymbol.visibility = ViewGroup.VISIBLE

        //根据响应数据中的天气图标代码，绘制天气图标
        context?.let {
            val iconCode = "_" + response.now.icon.replace("-", "_")
            if (WeatherUtils.isDrawableInRClass(it, iconCode)) {
                val drawables = WeatherUtils.getDrawableByName(it, iconCode)
                drawables.let {
                    binding.currentWeatherCard.ivWeatherIcon.setImageDrawable(drawables)
                }
                binding.currentWeatherCard.ivWeatherIcon.visibility = ViewGroup.VISIBLE
            } else {
                binding.currentWeatherCard.ivWeatherIcon.visibility = ViewGroup.GONE
            }

        }
        //内容
//        binding.currentWeatherCard.tvWeatherCondition.text="${response.now.text}     |     " +
//                "${response.now.windDir}     |     当前体感${response.now.feelsLike}°"
        //数据拼接，如 晴 | 北风3级 | 当前体感20度
        var constructText = ""
        if (response.now.text.isNotEmpty()) {
            constructText += response.now.text
        }
        if (response.now.windDir.isNotEmpty() && response.now.windScale.isNotEmpty()) {
            constructText += " | " + response.now.windDir + response.now.windScale + "级"
        }
        if (response.now.feelsLike.isNotEmpty()) {
            constructText += " | 当前体感" + response.now.feelsLike + "°"
        }
        if (constructText.isNotEmpty()) {
            binding.currentWeatherCard.tvWeatherCondition.text = constructText
        } else {
            binding.currentWeatherCard.tvWeatherCondition.text = "暂无数据"
        }

        //湿度
        binding.currentWeatherCard.tvHumidity.text = "${response.now.humidity}%"
        //风速
        binding.currentWeatherCard.tvWindSpeed.text = "${response.now.windSpeed}"
        //气压
        binding.currentWeatherCard.tvPressure.text = "${response.now.pressure}"


    }

    override fun getMainWeatherDataFailed(message: String) {
        hideLoading()
        binding.currentWeatherCard.llCurrentWeatherContainer.visibility = View.GONE
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show()
    }

    override fun getHourlyWeatherDataSuccess(response: WeatherHourlyResponse) {
        binding.hourlyForecast.root.visibility = View.VISIBLE
        //提交数据给适配器
        response.hourly?.let {hourlyList->
            (binding.hourlyForecast.rvHourlyForecast.adapter as HourTempAdapter).submitList(hourlyList)
        }


    }

    override fun getHourlyWeatherDataFailure(errorResponse: String) {
        binding.hourlyForecast.root.visibility = View.GONE
    }

    //获取24小时空气质量数据成功
    override fun getAirQualityDataSuccess(response: AirV1HourlyResponse) {
        binding.hourlyAirQuality.root.visibility = View.VISIBLE

        // 填充小时预报数据
        response.hours?.let { hourlyList ->
            (binding.hourlyAirQuality.rvHourlyAirQuality.adapter as? HourAirQualityAdapter)?.submitList(
                hourlyList
            )
        }


    }

    //获取24小时空气质量数据失败
    override fun getAirQualityDataFailure(errorResponse: String) {
        binding.hourlyAirQuality.root.visibility = View.GONE
    }

    //获取当前空气质量数据成功
    @SuppressLint("SetTextI18n")
    override fun getCurrentAirQualityDataSuccess(response: AirV1CurrentResponse) {
        binding.airQualityCard.root.visibility = View.VISIBLE
        // 填充空气质量卡片数据
        response.indexes?.let { indexList ->
            var airIndex = indexList[0]
            binding.airQualityCard.tvAirQualityIndex.text = airIndex.aqiDisplay

            // 设置进度条
            binding.airQualityCard.progressAirQuality.progress = airIndex.aqi.toInt()
            binding.airQualityCard.tvAirQualityLevel.text = airIndex.category

            // 设置背景色
            val gradientDrawable = GradientDrawable()
            gradientDrawable.shape = GradientDrawable.RECTANGLE
            gradientDrawable.cornerRadius = 16f // 圆角半径（像素）
            gradientDrawable.setColor(
                Color.rgb(
                    airIndex.color.red,
                    airIndex.color.green,
                    airIndex.color.blue
                )
            ) // 设置颜色
            binding.airQualityCard.tvAirQualityLevel.background = gradientDrawable

            // 填充健康建议
            if (airIndex.health.effect.isNotEmpty()) {
                binding.airQualityCard.tvAirQualityHealthEffect.visibility = View.VISIBLE
                binding.airQualityCard.tvAirQualityHealthEffect.text =
                    "健康影响： " + airIndex.health.effect
            } else {
                binding.airQualityCard.tvAirQualityHealthEffect.visibility = View.GONE
            }
        }

        //污染度及其浓度
        if (response.pollutants?.isNotEmpty() == true) {
            var pollutantMap = mutableMapOf<String, String>()
            pollutantMap["污染物"] = "浓度及单位"
            response.pollutants.let { pollutantList ->
                for (pollutant in pollutantList) {
                    if (pollutant.name.isNotEmpty()) {
                        var pollutantDescription = ""
                        pollutantDescription += pollutant.concentration.value.toString() + " " + pollutant.concentration.unit
                        pollutantMap[pollutant.name] = pollutantDescription
                    }
                }
            }
            if (response.pollutants.isNotEmpty()) {
                binding.airQualityCard.tlAirQuality.visibility = View.VISIBLE
                refreshAirQualityData(pollutantMap)
            } else {
                binding.airQualityCard.tlAirQuality.visibility = View.GONE
            }
        } else {
            binding.airQualityCard.tlAirQuality.visibility = View.GONE
        }

        //监测站数据
        var stationDescription = ""
        response.stations.let { stationList ->
            for (station in stationList) {
                if (station.name.isNotEmpty()) {
                    if (stationDescription.isNotEmpty()) {
                        stationDescription += " | "
                    }
                    stationDescription += station.name
                }
            }
        }
        if (stationDescription.isNotEmpty()) {
            binding.airQualityCard.tvAirQualityStations.visibility = View.VISIBLE
            binding.airQualityCard.tvAirQualityStations.text = "监测站： " + stationDescription
        } else {
            binding.airQualityCard.tvAirQualityStations.visibility = View.GONE
        }

    }
    fun refreshAirQualityData(dataMap: Map<String, String>) {
        // 清空现有行
        binding.airQualityCard.tlAirQuality.removeAllViews()
        dataMap.forEach { (key, value) ->
            addTableRow(key, value)
        }
    }

    fun addTableRow(name: String, age: String) {
        val row = TableRow(mActivity).apply {
            layoutParams = TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT
            )
            top = WeatherUtils.dip2px(context, 16f) // 设置行间距
            gravity = Gravity.CENTER  // 行内容居中
        }

        // No.1列
        val tvName = TextView(mActivity).apply {
            text = name
            gravity = Gravity.CENTER  // 单元格内容居中
            setTextColor("#ffffff".toColorInt())
            setPadding(WeatherUtils.dip2px(context, 16f), WeatherUtils.dip2px(context, 12f), WeatherUtils.dip2px(context, 16f), WeatherUtils.dip2px(context, 12f))
            layoutParams = TableRow.LayoutParams(
                0,
                TableRow.LayoutParams.WRAP_CONTENT,
                1f  // 关键：权重设为1
            )
        }

        // No.2列
        val tvAge = TextView(mActivity).apply {
            text = age
            gravity = Gravity.CENTER
            setTextColor("#ffffff".toColorInt())
            setPadding(WeatherUtils.dip2px(context, 16f), WeatherUtils.dip2px(context, 12f), WeatherUtils.dip2px(context, 16f), WeatherUtils.dip2px(context, 12f))
            layoutParams = TableRow.LayoutParams(
                0,
                TableRow.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        row.addView(tvName)
        row.addView(tvAge)
        binding.airQualityCard.tlAirQuality.addView(row)
    }
    override fun getCurrentAirQualityDataFailure(errorResponse: String) {
        binding.airQualityCard.root.visibility = View.VISIBLE
    }



    override fun refreshCityCityList(cityList: MutableList<ChangeCityBean>) {
        //为城市弹层传递数据
        dialog?.refreshCityList(cityList)
    }


    //----------------------------------------------------------------------------------------------
    /**
     * 刷新天气数据
     */
    fun refreshLocationWeatherData(
        latitude: String, longitude: String, cityName: String
    ) {
        //设置城市名称
        binding.topBar.tvCityName.text = cityName
        mPresenter?.setCityLocationParams(cityName, latitude, longitude)
        showLoading()
        // 请求主要天气数据
        mPresenter?.requestMainWeatherData() // 获取当前的天气质量也在这里




    }


    /**
     * 显示当前时间
     */
    fun showCurrentTime() {
        val currentTime = System.currentTimeMillis()
        // 格式化时间
        binding.topBar.tvCurrentTime.text =
            WeatherUtils.formatUTC(currentTime, "yyyy-MM-dd HH:mm:ss")
        // 在卡片显示星期
        binding.currentWeatherCard.tvWeekday.text = WeatherUtils.formatUTC(currentTime, "EEEE")
    }

    /**
     * 开始更新时间
     */
    fun startUpdateTime() {
        handler.post(updateTimeRunnable)
    }

    /**
     * 停止更新时间
     */
    fun stopUpdateTime() {
        handler.removeCallbacks(updateTimeRunnable)
    }


}